<html>
<head>
  <script src="jquery.js"></script>
  <script src="storage.js"></script>
  <script>
  Array.prototype.contains = function(obj){
    if(obj.gamertag){
     for(var i = 0; i < this.length; i++)
        if(this[i].gamertag == obj.gamertag)
            return true;
     return false;
    }
    else{
     for(var i = 0; i < this.length; i++)
        if(this[i].toString() == obj.toString())
            return true;
     return false;
    }
  };
  </script>
  <script>
  var alerts = new Array();
  var list;
  chrome.browserAction.setBadgeBackgroundColor({color:[200, 200, 200, 255]});
  chrome.browserAction.setBadgeText({text:"?"});

  var friends = 0;
  var friendsOnline = 0;
  var unread = 0;

  var onlineFriends = new Array();
  var offlineFriends = new Array();
  var onlineFriendsNew = new Array();
  var offlineFriendsNew = new Array();

  var unreadMessages = new Array();
  var unreadMessagesNew = new Array();

  var notification;
  var msgNotification;

  var waitingForList = false;
  var friendsList = "";
  var msgList = "";

  var loggingIn = false;
  var loginAttempt = 0;

  var hasUpdated = false;

  var t;
  var frameUpdateInterval;

  var locale = chrome.i18n.getMessage; // Short-hand
   
  // Message passing
  chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    switch(request.type){
        case "friendsList":
            if(friendsList == "" || msgList == ""){
                waitingForList = true;
                sendResponse({ok:false});
            }
            else if(request.now){
                waitingForList = true;
                sendResponse({ok:false});
                clearTimeout(t);
                update();
            }
            else{
              sendResponse(
                {
                    ok:true,
                    list: friendsList,
                    msgList:msgList,
                });
            }
            break;

        case "refreshStorage":
            loadSettings();
            sendResponse({ok:true});
            break;
        case "deleteMessage":
            
            $("#dropMsg").html(msgList);
            var el = $(".msg_idCont:contains('" + request.id + "')")[0];
            console.log(el);
            $(el).parent().parent().next().detach();
            $(el).parent().parent().detach();
            msgList = $("#dropMsg").html();
            sendResponse({ok:true});
            break;
        case "data":
            $("#drop").html(request.data);
            console.log("Data received");
            if(!hasUpdated)
                t = setTimeout("update();", 2500);
            break;
        default:
            sendResponse({}); // snub them.
            break;
     }
  });

  
  //READY
  $(document).ready(function (){
     
      loadSettings();

      frameUpdateInterval = setInterval("reloadFrame();", 15000);
      
  });

  //Main update function
  function update(){
      clearTimeout(t);
      if(loggingIn)
        return;
      hasUpdated = true;

      chrome.browserAction.setBadgeBackgroundColor({color:[200, 200, 200, 255]});
      chrome.browserAction.setBadgeText({text:"."});

      // ---------- LOAD FRIENDLIST --------------

      //Check if logged in
      if($("#drop").text().length.toString() != "0"){
        //Build friendslist
        friendsList = "";
        fArray = new Array();
        $("#drop").children().filter("#fc-online").children().filter("dd").each(function (){
            fArray.push({
                gt: $(this).find(".fc-gtag-link").text(),
                presence: "Online",
                desc: $(this).find(".fc-presence-text").text()
            });
        });
        friendsOnline = fArray.length;
        $("#drop").children().filter("#fc-offline").children().filter("dd").each(function (){
            fArray.push({
                gt: $(this).find(".fc-gtag-link").text(),
                presence: "Offline",
                desc: $(this).find(".fc-presence-text").text()
            });
        });

        friends = fArray.length;

        for (var i = 0; i < friends; i++)
        {
            f = fArray[i];
            var str = "<tr class='XbcTableFriend" + f.presence + "'>";
              str += "<td title='" + f.presence + "'>" +
                       "<a href='javascript:void(0);' onclick='gamertagClick(this,evt);' onmouseover='closeOnClick=false;' onmouseout='closeOnClick=true' class='XbcGamerTag'>" + 
                            f.gt + 
                       "</a>" +
                     "</td>";
            var desc = f.desc;
            var desc2 = "";
            if(desc.indexOf(" - ") > 0){
               desc2 = desc.split(" - ")[1].trim();
               desc = desc.split(" - ")[0].trim();
               if(desc2.length > 0)
                  desc2 = "onmouseover=\"onlineOver(this);\" onmouseout=\"onlineOut(this);\" title='" + desc2 + "'";
            }
            if(f.presence == "Online")
                onlineFriendsNew.push({gamertag:f.gt,desc:desc});
            else
                offlineFriendsNew.push({gamertag:f.gt,desc:desc});
            str += "<td " + desc2 + ">" + desc + "</td>";
            str += "</tr>";
            friendsList += str;
        }

        chrome.browserAction.setBadgeText({text:".."});
        
        unread = 0;
        //completeUpdate();
        updateMsg();
      }
      
      /*
      else{
        //If logged out
        
        if(settings["autologin"].value == "true"){
           loginAttempt++;
           if(loginAttempt <= 3){
             friendsList = "<tr><th colspan='2'>" + locale("auto_attempt") + " " + loginAttempt + "</img></th></tr>" 
                        +"<tr><th colspan='2'><img src='ajax-loader.gif'></img></th></tr>"
             var al = setTimeout("autoLogin();", 100);
           }
           else{
             friendsList = "<tr><th colspan='2'>" + locale("auto_fail") + "</<th></tr>"
                    + "<tr><th colspan='2'><a href='http://live.xbox.com/'>" + locale("man_click") + "</a></th></tr>"
                    + "<tr><th colspan='2'><button onclick='requestList(true);'>" + locale("man_refresh") +  "</button></th></tr>";
             loginAttempt = 0;
           }
        }
        else{
          friendsList = "<tr><th colspan='2'>" + locale("not_logged_in") + "</<th></tr>"
                    + "<tr><th colspan='2'><a href='http://live.xbox.com/'>" + locale("man_click") + "</a></th></tr>"
                    + "<tr><th colspan='2'><button onclick='requestList(true);'>" + locale("man_refresh") +  "</button></th></tr>";
        }
        friends = friendsOnline = unread = -1;
        msgList = friendsList;
        completeUpdate();
      }
      */
          
    t=setTimeout("update();", settings["interval"].value*1000);
  }
  function updateMsg(){
    $("#dropMsg").load("http://live.xbox.com/sv-SE/MessageCenter #messages", function(){
        unread = $("#dropMsg").find("#msgcount").text();
        unread = unread.substr(1, unread.length - 2);
        msgList = "";
        $("#dropMsg div dl").children().each(function(){
            var msgId = $(this).attr("id").replace("msg", "");
            var gt = $(this).find(".gamertag").text();
            var text = $(this).find(".messagetext").text().trim();
            var unread = $(this).attr("class").indexOf("unread") > 0;
            msgList += ("<tr class='XbcMessage" + (unread ? "Unread" : "Read" ) + "'>" + 
                            "<td class='expandMsg'>" +
                                "<span class='msg_idCont' style='display:none;'>" + msgId + "</span>" + 
                                "<a href='javascript:;' onclick=\"openMsg('" + msgId + "', this);\">" + 
                                    "<img src='plus.png' ></img>" + 
                                "</a>" +
                            "</td>" +
                            "<td>" + gt + "<span class='loadingMsg'><img src='ajax-loader-kit.gif'></img></span></td>" +
                            "<td>" + text + "</td></a>" +
                        "</tr>");
            msgList += ("<tr class='msgBody' style='white-space:normal;'></tr>");

            if($(this).attr("class").indexOf("unread") > 0){
                unreadMessagesNew.push({gt:gt,text:text});
                unreadMessagesNew[unreadMessagesNew.length - 1].toString = function(){ return this.gt + this.text;};
            }
        });
        msgList += "<tr style='display:none;><td></td></tr>";
        
        completeUpdate();
    });
  }

  //Update/refresh UI and send list to popup
  function completeUpdate(){
    var temp = "F:" + friendsOnline.toString();
    if(unread > 0){
      chrome.browserAction.setBadgeBackgroundColor({color:[0, 240, 0, 255]});
      temp = "U:" + unread.toString();
    }
    else
      chrome.browserAction.setBadgeBackgroundColor({color:[50, 200, 0, 255]});

    if(friends == -1){
      chrome.browserAction.setBadgeText({text:"?"});
      chrome.browserAction.setBadgeBackgroundColor({color:[200, 200, 200, 255]});
      chrome.browserAction.setTitle({title:"Xbox LIVE Center"});
    }
    else{
      chrome.browserAction.setBadgeText({text:temp});
      chrome.browserAction.setTitle({title:
                        locale("friendsOnline") + ": " + friendsOnline + "/" + friends + "\r\n" +
                        locale("unreadMsgs") + ": " + unread});
    }
    
    //Notifications
    if(friends != -1){
//        unreadMessagesNew.push({gt:"ouT Fury",text:"LoLoL"}); //TESTING
//        unreadMessagesNew.push({gt:"ouT Fury",text:"LoLoL"}); //TESTING
        var newMessages = new Array();
        var newOnline = new Array();
        for(var i = 0; i < onlineFriendsNew.length; i++){
            if(!onlineFriends.contains(onlineFriendsNew[i]) && offlineFriends.contains(onlineFriendsNew[i]))
                newOnline.push(onlineFriendsNew[i]);
        }
        for(var i = 0; i < unreadMessagesNew.length; i++){
            if(!unreadMessages.contains(unreadMessagesNew[i]))
                newMessages.push(unreadMessagesNew[i]);
        }
        
        if(newOnline.length > 1){
            notification = webkitNotifications.createNotification(
              'icon48.png',  // icon url - can be relative
              locale("not_multiOnlineFriends_head").replace("{#}", newOnline.length.toString()),  // notification title
              locale("not_multiOnlineFriends_body").replace("{#}", newOnline.length.toString())  // notification body text
            );
        }
        else if(newOnline.length == 1){
            notification = webkitNotifications.createNotification(
              'icon48.png',  // icon url - can be relative
              locale("not_onlineFriend_head").replace("{GT}", newOnline[0].gamertag).replace("{D}", newOnline[0].desc),  // notification title
              locale("not_onlineFriend_body").replace("{GT}", newOnline[0].gamertag).replace("{D}", newOnline[0].desc)  // notification body text
            );
        }
        if(newOnline.length > 0 && settings["notShow"].value){
            notification.show();
            setTimeout("closeNotification('online')", settings["notDelay"].value*1000);
        }

        if(newMessages.length > 1){
            
            msgNotification = webkitNotifications.createNotification(
              'icon48.png',  // icon url - can be relative
              locale("not_multiNewMsgs_head").replace("{#}", newMessages.length),  // notification title
              locale("not_multiNewMsgs_body").replace("{#}", newMessages.length)  // notification body text
            );
        }
        else if(newMessages.length == 1){
            msgNotification = webkitNotifications.createNotification(
              'icon48.png',  // icon url - can be relative
              locale("not_newMessage_head").replace("{GT}", newMessages[0].gt).replace("{T}", newMessages[0].text),  // notification title
              locale("not_newMessage_body").replace("{GT}", newMessages[0].gt).replace("{T}", newMessages[0].text)  // notification body text
            );
        }
        if(newMessages.length > 0 && settings["notShow"].value){
            msgNotification.show();
            setTimeout("closeNotification('msg')", settings["notDelay"].value*1000);
        }
        
//        offlineFriendsNew.push(onlineFriendsNew.pop()); // TESTING
//        onlineFriendsNew.push(offlineFriendsNew.pop()); // TESTING
        onlineFriends = onlineFriendsNew;
        onlineFriendsNew = new Array();
        offlineFriends = offlineFriendsNew;
        offlineFriendsNew = new Array();
        unreadMessages = unreadMessagesNew;
        unreadMessagesNew = new Array();
    }

    // If popup is waiting
    if(waitingForList){
          waitingForList = false;
          chrome.extension.sendRequest(
          {
              type: "waitingList",
              list:friendsList,
              msgList:msgList,
          }
          , function(response) {
              console.log("WaitingList sent");
        });
    }
  }
  function autoLogin(){
    loggingIn = true;
    

   $("#alFrame")[0].onload = function() {contAL();};
   $("#alFrame")[0].src = "http://live.xbox.com/";

  }
  function contAL(){
    loggingIn = false;
    waitingForList = true;
    update();
  }
  function reloadFrame(){
    $("#fFrame")[0].src = "about:blank";
    $("#fFrame")[0].src = "http://live.xbox.com/FriendCenter";
  }
  function closeNotification(type){
    if(type == "msg")
        msgNotification.cancel();
    else
        notification.cancel();
  }
  </script>
</head>
<body>
<div id="drop" style="display:none;"></div>
<div id="dropMsg" style="display:none;"></div>
<canvas id="canvas" width="19" height="19"></canvas>
<iframe id="alFrame" src="http://live.xbox.com/sv-SE/FriendCenter"></iframe>
<iframe id="fFrame" src="http://live.xbox.com/FriendCenter"></iframe>
</body>
</html>
